#pragma GCC optimize(2)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <vector>

using namespace std;
using LL = long long;
const int N = 510, M = N * N;


LL n, m, idx;
struct Edge{
    LL a, b, v;

    bool operator< (const Edge & W)const{
        return v > W.v;
    }
}e[M];
LL a[N];
int p[N];



LL qmi(LL a, LL b){
    LL res = 1;
    while(b){
        if(b & 1) res = res * a % m;
        b >>= 1;
        a = a * a % m;
    }
    return res % m;
}

int find(int x){
    if(x != p[x]){
        p[x] = find(p[x]);
    }
    return p[x];
}

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n >> m;
    idx = 0;

    for(int i = 1; i <= n; i ++) cin >> a[i], p[i] = i;

    for(int i = 1; i <= n; i ++){
        for(int j = i + 1; j <= n; j ++){
            e[idx ++] = {i, j, (qmi(a[i], a[j]) + qmi(a[j], a[i])) % m};
        }
    }

    sort(e, e + idx);

    LL res = 0;
    for(int i = 0; i < idx; i ++){
        int a = e[i].a, b = e[i].b;
        LL v = e[i].v;

        int fa = find(a), fb = find(b);

        if(fa != fb){
            p[fa] = fb;
            res += v;
       //     cout << "a: " << a << " b: " << b << " v: " << v << '\n';
        }
    }

    cout << res << '\n';

    return 0;
}